#!/usr/bin/env python
# coding: utf-8
# from typing import Dict, Union
from datetime import datetime, timedelta
import freeswitch
from rediscluster import client
import time
import random
import demjson
import json


##待优化,使用内存作为缓存，不再每次都使用命令查询SIP USER
def handler(session, args):  # args is string
    session.setAutoHangup(False)  ##设置不要自动挂机,否则当此脚本执行完,会自动挂机
    gatewayContractStr = None  ## 网关联系地址

    api = freeswitch.API()  ##freeswitch的API
    sipUserSuffix = session.getVariable("sipUserSuffix")
    channelIndex = session.getVariable("channelIndex")
    targetPhone = session.getVariable("targetPhone")
    localhostIp = "172.16.200.60"
    gatewayUser = "199000000" + sipUserSuffix

    freeswitch.consoleLog("INFO",
                          "sipUserSuffix:" + sipUserSuffix + " channelIndex:" + channelIndex + " targetPhone:" + targetPhone)  ##打印
    ##fscall随机选择了一个gateway,这里要做在先检查
    # 假如选到的gateway为空闲的,就停止循环,否则继续(要注意判断session的状态,否则可能有死循环)
    gatewayStatus = api.executeString(
        "sofia status profile internal user " + gatewayUser + "@" + localhostIp)  ##查询当前gateway是否在线
    beginIndex = gatewayStatus.find("User")  ##截取字符串
    if beginIndex > -1:  ##假如不为None,就是gateway已经在线
        ##获取注册contact头
        contactBeginIndex = gatewayStatus.find("sip:" + gatewayUser + "@")
        contactEndIndex = gatewayStatus.find(">")
        gatewayContractStr = gatewayStatus[contactBeginIndex:contactEndIndex]
    else:
        freeswitch.consoleLog("ERROR", "网关" + gatewayUser + "尚未注册")  ##打印gateway线路日志
        session.streamFile("/usr/local/freeswitch/sounds/user/lineBusy.wav", "5")  ##播放忙音语音
        session.hangup("gateway_not_registered")  ##直接挂他机
        ##Create Custom event
        custom_msg = "sessionId: " + session.get_uuid() + ",gatewayUser:" + gatewayUser
        e = freeswitch.Event("custom", "dial::gateway_not_registered")
        e.addHeader("sessionId", session.get_uuid())
        e.addHeader("gatewayChannelIndex", channelIndex)
        e.addHeader("gatewaySipUser", gatewayUser)
        e.addBody(custom_msg)
        e.fire()
        return

    if gatewayContractStr is not None:
        "假如不空,就用它呼出,假如为空,就表示全部gateway都忙线"
        session.setVariable("contactStr", gatewayContractStr)  ##设置外呼字符串的参数
        freeswitch.consoleLog("DEBUG", "网关联系地址" + gatewayContractStr)  ##打印
    else:
        session.hangup("ORIGINATOR_CANCEL")
